package top.ffhome.game.ch05fix;

import top.ffhome.game.ch05.MapFactory;

import javax.swing.*;
import java.awt.*;

public class GameFrame extends BufferFrame {
    private int grade = 0;
    private Image pic[] = null;
    private byte[][] map = null;
    private int mapRow = 0, mapColumn = 0, leftX = 0, leftY = 0;

    public GameFrame() {
        super("推箱子");
        setSize(600, 600);
        setVisible(true);
        setResizable(false);
        setLocation(300, 20);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container cont = getContentPane();
        cont.setLayout(null);
        cont.setBackground(Color.black);
        setFocusable(true);
        getPic();
        initMap();
    }

    private void getPic() {
        String path = this.getClass().getClassLoader().getResource("").getPath();
        pic = new Image[14];
        for (int i = 0; i <= 13; i++) {
            pic[i] = Toolkit.getDefaultToolkit().getImage(path + "ch05/images/pic" + i + ".jpg");
        }
    }

    private void initMap() {
        map = MapFactory.getMap(grade);
        getMapSizeAndPosition();
    }

    private void getMapSizeAndPosition() {
        mapRow = map.length;
        mapColumn = map[0].length;
        leftX = (this.getWidth() - mapColumn * 30) / 2;
        leftY = (this.getHeight() - mapRow * 30) / 2;
    }

    @Override
    public void paintBuffer(Graphics g) {
        for (int i = 0; i < mapRow; i++) {
            for (int j = 0; j < mapColumn; j++) {
                if (map[i][j] != 0) {
                    g.drawImage(pic[map[i][j]], leftX + j * 30, leftY + i * 30, this);
                }
            }
        }
        g.setColor(Color.RED);
        g.setFont(new Font("楷体_2312", Font.BOLD, 30));
        g.drawString("现在是第", 150, 140);
        g.drawString(String.valueOf(grade + 1), 310, 140);
        g.drawString("关", 360, 140);
    }

    public static void main(String[] args) {
        new GameFrame();
    }
}
